package com.mew.user.events.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mew.common.dc.db.ProfileService;
import com.mew.common.dc.mapper.SignMapper;
import com.mew.common.dc.redis.LevelConfigRedisService;
import com.mew.common.dc.redis.UserProfileRedisService;
import com.mew.common.enm.GoldProcessType;
import com.mew.common.entity.events.Sign;
import com.mew.common.entity.user.Profile;
import com.mew.common.exception.ResponseCode;
import com.mew.common.rest.events.SignInfoResponseMessage;
import com.mew.common.rest.events.SignResponseMessage;
import com.mew.common.rest.user.UserMoneyResponseMessage;
import com.mew.common.util.NumberUtil;
import com.mew.common.util.StringUtils;
import com.mew.user.config.EventsLastingConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;

/**
 * 该功能 如果大面积推广 新优化
 */
@Service
@Slf4j
public class UserSignService {

    @Autowired
    private SignMapper signMapper;
    @Autowired
    private ProfileService profileService;
    @Autowired
    private EventsLastingConfig eventsLastingConfig;

    public SignInfoResponseMessage signInfo(long userId){
        Sign sign = getSign(userId);
        SignInfoResponseMessage message = SignInfoResponseMessage.toMsg(sign);
        message.setFisrt7(eventsLastingConfig.getFirst7());
        message.setRuleA((eventsLastingConfig.getSignA()));
        message.setRuleB((eventsLastingConfig.getSignB()));
        message.setRuleC((eventsLastingConfig.getSignC()));
        message.setRuleD((eventsLastingConfig.getSignD()));

        int[] signInfo = Arrays.stream(sign.getSignInfo().split(",")).mapToInt(Integer::parseInt).toArray();
        int day = Integer.parseInt(DateUtil.format(new Date(), "dd"));
        message.setSign(signInfo[day - 1]);

        return message;
    }

    Sign getSign(long userId){
        Sign sign = signMapper.selectById(userId);
        String month = DateUtil.format(new Date(), "yyyyMM");
        if (null==sign||!month.equals(DateUtil.format(sign.getStartDate(), "yyyyMM"))||StringUtils.isEmpty(sign.getSignInfo())||sign.getSignInfo().split(",").length<28){
            sign = createSign(userId);
        }

        return sign;
    }


    private Sign createSign(long userId) {
        //这个月的天数
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        int maximum = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);;

        //新的
        Sign sign = Sign.builder().userId(userId).signInfo(StrUtil.join(",",new int[maximum])).build();
        sign.init();
        signMapper.replace(sign);

        return sign;
    }

    public SignResponseMessage sign(long userId){
        int day = Integer.parseInt(DateUtil.format(new Date(), "dd"));

        return signDay(userId, day);
    }

    public void sign(long userId,SignInfoResponseMessage message){
        int day = Integer.parseInt(DateUtil.format(new Date(), "dd"));
        signDay(userId, day,message);
    }

    public SignResponseMessage signDay(long userId, int day) {
        int today = Integer.parseInt(DateUtil.format(new Date(), "dd"));
        //补签 签到 天数不能大于今天
        if (day>today){
            return new SignResponseMessage().buildByResponseCode(ResponseCode.SignNot);
        }


        Sign sign = getSign(userId);

        String signInfoStr = sign.getSignInfo();
        int[] signInfo = Arrays.stream(signInfoStr.split(",")).mapToInt(Integer::parseInt).toArray();

        //第几天
        int isSign = signInfo[day - 1];

        if (isSign==1){
            return new SignResponseMessage().buildByResponseCode(ResponseCode.SignDID);
        }
        signInfo[day - 1] = 1;

        SignResponseMessage message = new SignResponseMessage();
        //签到金币
        Long signGold = 0l;
        int sum = Arrays.stream(signInfo).sum();
        if (sum<8){
            signGold += Long.parseLong(eventsLastingConfig.getFirst7().split(",")[sum-1]);
        }

        //连续签
        message.setAStatus(sign.getAStatus()==1?2:(sum>=7?1:0));
        message.setBStatus(sign.getBStatus()==1?2:(sum>=15?1:0));
        message.setCStatus(sign.getCStatus()==1?2:(sum>=22?1:0));
        message.setDStatus(sign.getDStatus()==1?2:(sum>=28?1:0));

        //更新
        String join = StrUtil.join(",", signInfo);
        Sign newS = Sign.builder().signInfo(join).build();
        int update = signMapper.update(newS, new LambdaQueryWrapper<Sign>().eq(Sign::getUserId, userId).eq(Sign::getSignInfo, signInfoStr));
        if (update==0){
            return new SignResponseMessage().buildByResponseCode(ResponseCode.SignDID);
        }

        //没加钱
        Profile profile = profileService.getRedisProfileById(userId);
        profileService.doGold(profile,signGold, GoldProcessType.Sign);

        UserMoneyResponseMessage userMoney = message.getUserMoneyResponseMessage();
        userMoney.setGoldNumber(profile.getGoldNumber());
        userMoney.setJewelNumber(profile.getGoldNumber());

        return message;
    }

    public void signDay(long userId, int day,SignInfoResponseMessage message) {
        int today = Integer.parseInt(DateUtil.format(new Date(), "dd"));
        //补签 签到 天数不能大于今天
        if (day>today){
             message.buildByResponseCode(ResponseCode.SignNot);
             return;
        }

        Sign sign = getSign(userId);

        String signInfoStr = sign.getSignInfo();
        int[] signInfo = Arrays.stream(signInfoStr.split(",")).mapToInt(Integer::parseInt).toArray();

        //第几天
        int isSign = signInfo[day - 1];

        if (isSign==1){
            Profile profile = profileService.getRedisProfileById(userId);
            UserMoneyResponseMessage userMoney = message.getUserMoneyResponseMessage();
            userMoney.setGoldNumber(profile.getGoldNumber());
            userMoney.setJewelNumber(profile.getJewelNumber());
            message.sign = 1;
            return;
        }
        signInfo[day - 1] = 1;


        //签到金币
        Long signGold = 0l;
        int sum = Arrays.stream(signInfo).sum();
        if (sum<8){
            signGold += Long.parseLong(eventsLastingConfig.getFirst7().split(",")[sum-1]);
        }

        //连续签

        message.setAStatus(sign.getAStatus()==2?2:(sum>=7?1:0));
        message.setBStatus(sign.getBStatus()==2?2:(sum>=15?1:0));
        message.setCStatus(sign.getCStatus()==2?2:(sum>=22?1:0));
        message.setDStatus(sign.getDStatus()==2?2:(sum>=28?1:0));

        //更新
        String join = StrUtil.join(",", signInfo);
        Sign newS = Sign.builder().signInfo(join).build();
        int update = signMapper.update(newS, new LambdaQueryWrapper<Sign>().eq(Sign::getUserId, userId).eq(Sign::getSignInfo, signInfoStr));
        if (update==0){
            message.buildByResponseCode(ResponseCode.SignDID);
            return;
        }

        Profile profile = profileService.getRedisProfileById(userId);
        profileService.doGold(profile,signGold, GoldProcessType.Sign);

        UserMoneyResponseMessage userMoney = message.getUserMoneyResponseMessage();

        userMoney.setGoldNumber(profile.getGoldNumber());
        userMoney.setJewelNumber(profile.getJewelNumber());

    }

    public SignResponseMessage gain(long userId, int type){
        Sign sign = getSign(userId);
        String signInfoStr = sign.getSignInfo();
        int[] signInfo = Arrays.stream(signInfoStr.split(",")).mapToInt(Integer::parseInt).toArray();
        int sum = Arrays.stream(signInfo).sum();
        if (type<1||type>4){
            return new SignResponseMessage().buildByResponseCode(ResponseCode.SignGain);
        }
        if ((type==1&&sum<7)||(type==2&&sum<15)||(type==3&&sum<22)||(type==4&&sum<28)){
            return new SignResponseMessage().buildByResponseCode(ResponseCode.SignSignTimes);
        }
        if ((type==1&&sign.getAStatus()==1)||(type==2&&sign.getBStatus()==1)||(type==3&&sign.getCStatus()==1)||(type==4&&sign.getDStatus()==1)){
            return new SignResponseMessage().buildByResponseCode(ResponseCode.SignGain);
        }

        SignResponseMessage message = new SignResponseMessage();
        message.setAStatus(sign.getAStatus()==2?2:(sum>=7?1:0));
        message.setBStatus(sign.getBStatus()==2?2:(sum>=15?1:0));
        message.setCStatus(sign.getCStatus()==2?2:(sum>=22?1:0));
        message.setDStatus(sign.getDStatus()==2?2:(sum>=28?1:0));
        int update = signMapper.gain(userId,type);

        if (update==0){
            return new SignResponseMessage().buildByResponseCode(ResponseCode.SignGain);
        }

        long number = 0;

        //可以签了
        if (type==1){
            number = eventsLastingConfig.getSignA();
            message.setAStatus(2);
        }else if (type==2){
            number = (eventsLastingConfig.getSignB());
            message.setBStatus(2);
        }else if (type==3){
            number = (eventsLastingConfig.getSignC());
            message.setCStatus(2);
        }else if (type==4){
            number = (eventsLastingConfig.getSignD());
            message.setDStatus(2);
        }

        Profile profile = profileService.getRedisProfileById(userId);
        profileService.doGold(profile,number, GoldProcessType.Sign);

        UserMoneyResponseMessage userMoney = message.getUserMoneyResponseMessage();
        userMoney.setGoldNumber(profile.getGoldNumber());
        userMoney.setJewelNumber(profile.getJewelNumber());

        return message;
    }


//    public static void main(String[] args) {
//        int[] signInfo = new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,};
//        signInfo[3] = 1;
//        String join = StrUtil.join(",", signInfo);
//        System.out.println(join);
//    }
}
